package cn.collin.commons.web.filter;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * logging request parameters and attributes
 * 
 * http://collincode.googlecode.com
 * 
 * @author collin.code@gmail.com
 * 
 */
public class RequestLogFilter implements Filter {
	private static final Log LOGGER = LogFactory.getLog(RequestLogFilter.class);

	public void init(FilterConfig filterConfig) throws ServletException {
		LOGGER.info("RequestLogFilter initialized.");
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		if (LOGGER.isDebugEnabled()) {
			StringBuffer sb = new StringBuffer();
			Enumeration<String> names;
			sb.append("Logging : \n");
			sb.append("--- Request URL: ---\n").append("\t").append(
					((HttpServletRequest) request).getRequestURL())
					.append("\n");
			names = request.getParameterNames();
			sb.append("--- Request Parameters: ---\n");
			while (names.hasMoreElements()) {
				String name = names.nextElement();
				sb.append("\t").append(name).append(":").append(
						request.getParameter(name)).append("\n");
			}

			names = request.getAttributeNames();
			sb.append("--- Request Attributes: ---\n");
			while (names.hasMoreElements()) {
				String name = names.nextElement();
				sb.append("\t").append(name).append(":").append(
						request.getAttribute(name)).append("\n");
			}

			LOGGER.debug(sb.toString());
		}
		chain.doFilter(request, response);
	}

	public void destroy() {
		LOGGER.debug("RequestLogFilter destroyed.");
	}
}
